package com.hjimi.ski.view.service;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.hjimi.ski.app.MyApplication;
import com.hjimi.ski.config.Constant;
import com.hjimi.ski.utils.SpUtil;
import com.hjimi.ski.view.event.MqttDeviceInfoEvent;

import org.fusesource.hawtbuf.Buffer;
import org.fusesource.hawtbuf.UTF8Buffer;
import org.fusesource.mqtt.client.Callback;
import org.fusesource.mqtt.client.CallbackConnection;
import org.fusesource.mqtt.client.Listener;
import org.fusesource.mqtt.client.MQTT;
import org.fusesource.mqtt.client.QoS;
import org.fusesource.mqtt.client.Topic;
import org.greenrobot.eventbus.EventBus;

import java.nio.charset.StandardCharsets;


/**
 * Created By 孙岩 13934584320
 * on 2023/11/27
 */
public class BindMqttService extends Service {
    //    private MqttConnectOptions conOpt;
    private IGetMessageCallBack mIGetMessageCallBack;
    private String host = "tcp://39.100.65.124:1883";
    private String userName = "sunyan";
    private String passWord = "sunyan123";
    private String clientId = "AndroidClient" + SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getInt(Constant.device_info_id, 0);

    private static CallbackConnection connection;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onCreate() {
        super.onCreate();
//        sendMqtt();
        // 创建 MQTT 客户端连接参数
        createMqtt();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void createMqtt() {
        MQTT mqtt = new MQTT();
        try {
            mqtt.setHost(host);
            mqtt.setUserName(userName);
            mqtt.setPassword(passWord);
            mqtt.setClientId(clientId);
            mqtt.setWillTopic(Constant.UP_DOWN_DESC + SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getInt(Constant.device_info_id, 0));
            mqtt.setWillMessage("0");
            mqtt.setWillQos(QoS.AT_MOST_ONCE);
            mqtt.setKeepAlive(Short.parseShort("10"));

            //建立连接
            connection = mqtt.callbackConnection();
            connection.connect((new Callback<Void>() {
                @Override
                public void onSuccess(Void value) {
                    Log.d("sunyan", "连接成功");
                    publish(Constant.UP_DOWN_DESC + SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getInt(Constant.device_info_id, 0), "1");
                    //订阅主题0主题
                    Topic[] topics = {new Topic(Constant.B_RESULT + SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getInt(Constant.device_info_id, 33), QoS.AT_MOST_ONCE)};
                    Log.d("sunyan", "订阅主题= device_info_id=" + Constant.U_RESULT + SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getInt(Constant.device_info_id, 444));
                    connection.subscribe(topics, new Callback<byte[]>() {
                        @Override
                        public void onSuccess(byte[] value) {
                            Log.d("sunyan", "订阅消息成功");
                        }

                        @Override
                        public void onFailure(Throwable value) {
                            Log.d("sunyan", "订阅消息失败"+value.toString());
                        }
                    });
                }

                @Override
                public void onFailure(Throwable value) {
                    Log.d("sunyan", "连接失败");
                }
            }));

            connection.listener(new Listener() {
                @Override
                public void onConnected() {
                    Log.d("sunyan", "onConnected");
                }

                @Override
                public void onDisconnected() {
                    Log.d("sunyan", "onDisconnected");
                }

                @Override
                public void onPublish(UTF8Buffer topic, Buffer body, Runnable ack) {

                    //表示是o主题
                    if (topic.toString().equals(Constant.B_RESULT + SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getInt(Constant.device_info_id, 44))) {
                        byte[] data = body.toByteArray();
                        // 处理数据...
                        // 例如，如果你知道这些数据是UTF-8编码的字符串，你可以这样转换它：
                        String stringData = new String(data, StandardCharsets.UTF_8);

                        EventBus.getDefault().post(new MqttDeviceInfoEvent());
                    }
                }

                @Override
                public void onFailure(Throwable value) {
                    Log.d("sunyan", "onFailure");
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            Log.d("sunyan", "错误" + e.toString());
        }
    }

    public static void publish(String topic, String name) {
        try {
            connection.publish(topic, name.getBytes(), QoS.AT_MOST_ONCE, false, new Callback<Void>() {
                @Override
                public void onSuccess(Void value) {
                    Log.d("sunyan","发布主题成功"+topic + "-------------"+name);
                }

                @Override
                public void onFailure(Throwable value) {
                    Log.d("sunyan","发布主题" +"************************"+name+"-----"+value.toString());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
